package ccm.communicate.file;

import ccm.common.CCMConfigManager;
import ccm.component.override.JButton;
import ccm.component.override.JLabel;
import ccm.component.override.TitledBorder;
import ccm.component.override.VFlowLayout;

import javax.swing.*;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class FileSaverConfigJPanel extends JPanel
{
    /**
     * 保存被控制的串口
     */
    protected final FileSaver fileSaver;
    protected final JLabel infoJLabel;


    FileSaverConfigJPanel(FileSaver fileSaverIn) throws NullPointerException
    {
        super();
        setBorder(new TitledBorder("记录设置"));
        setLayout(new VFlowLayout());
        fileSaver=fileSaverIn;
        add(infoJLabel=new JLabel());
        JButton setDirJButton=new JButton("设置数据记录路径");
        add(setDirJButton);
        setDirJButton.addActionListener(e->
        {
            JFileChooser fileChooser=new JFileChooser(CCMConfigManager.getString("ccm/communicate/file/FileSaver/dir"));
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal=fileChooser.showOpenDialog(fileChooser);
            if(returnVal==JFileChooser.APPROVE_OPTION)
            {
                fileSaver.setFileSaverDir(fileChooser.getSelectedFile().getAbsolutePath());
            }
        });
        JButton openDirJButton=new JButton("打开数据记录路径");
        add(openDirJButton);
        openDirJButton.addActionListener(e->
        {
            try
            {
                Runtime.getRuntime().exec("explorer.exe /root,"+CCMConfigManager.getString("ccm/communicate/file/FileSaver/dir").replace('/','\\'));
            }catch(IOException ignored){}
        });
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()->
        {
            try
            {
                infoJLabel.setText(fileSaverIn.getInfoText());
            }catch(Exception e)
            {
                e.printStackTrace();
            }
        },0,1,TimeUnit.SECONDS);
    }

}
